<template>
  <div>
    <!--引用表格-->
    <BasicTable :rowSelection="rowSelection" @register="registerTable">
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button v-if="!isHistory && hasPermission('act:model:add')"
                  preIcon="ant-design:plus-outlined" type="primary" @click="handleAdd">新增
        </a-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item v-if="hasPermission('act:model:delete')" key="1"
                           @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"/>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button
          >批量操作
            <Icon icon="mdi:chevron-down"/>
          </a-button>
        </a-dropdown>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <TableAction :actions="getTableAction(record)"
                     :dropDownActions="getDropDownAction(record)"/>
      </template>
      <!--字段回显插槽-->
      <template #bodyCell="{ column, record, index, text }"></template>
    </BasicTable>
    <!-- 表单区域 -->
    <ActModelModal @register="registerModal" @success="handleSuccess"/>
    <!-- 流程部署弹框区域 -->
    <ActModelDeply @register="registerDeployModal" @success="handleDeploySuccess"/>
    <!-- 显示模板Xml内容 -->
    <ActModelXmlView ref="registerModalXmlView"/>

    <ActModelBpmnModeler @register="registerEditorModal"/>

    <template>
      <a-modal v-model:visible="deploySelectVisible" :footer="null" title="请选择流程部署工具">
        <p style="width: 100%; line-height: 150px; text-align: center">
          <a-button key="back" @click="handleDeploySelected(1)">原生编辑器</a-button>
          <a-divider type="vertical"/>
          <a-button key="submit" type="primary" @click="handleDeploySelected(2)">Bpmn编辑器
          </a-button>
        </p>
      </a-modal>
    </template>
  </div>
</template>

<script lang="ts" name="model-inAddModelDto" setup>
import {computed, ref} from 'vue'
import {BasicTable, TableAction} from '/@/components/Table'
import {useModal} from '/@/components/Modal'
import {useListPage} from '/@/hooks/system/useListPage'
import ActModelModal from './components/ActModelModal.vue'
import ActModelDeply from './components/ActModelDeploy.vue'
import ActModelXmlView from './components/ActModelXmlView.vue'
import {columns, searchFormSchema} from './ActModel.data'
import {batchDelete, copy, deleteOne, listHistoryPage, listPage} from './ActModel.api'
import {usePermission} from '/@/hooks/web/usePermission'
import ActModelBpmnModeler from '@/views/activiti/model/components/ActModelBpmnModeler.vue'
import {useRoute} from "vue-router";
import {useGo} from "@/hooks/web/usePage";

const {hasPermission} = usePermission()
const route = useRoute()
const go = useGo()

const procModelKey = route.params?.modelKey ?? -1
const isHistory = computed(() => route.path.includes('history'))

const registerModalXmlView = ref()

//注册model
const [registerModal, {openModal}] = useModal()
//注册流程部署弹框
const [registerDeployModal, {openModal: openDeployModal}] = useModal()
const [registerEditorModal, {openModal: openEditorModal}] = useModal()

//注册table数据
const {tableContext} = useListPage({
  tableProps: {
    title: '流程模板',
    api: isHistory.value ? listHistoryPage : listPage,
    columns,
    canResize: false,
    formConfig: {
      //labelWidth: 120,
      schemas: isHistory.value ? [] : searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      showActionButtonGroup: !isHistory.value,
      fieldMapToNumber: [],
      fieldMapToTime: [],
    },
    actionColumn: {
      width: 280,
      fixed: 'right',
    },
    beforeFetch: (params) => {
      console.log('history???', isHistory.value, procModelKey)
      console.log('beforeFetch', params)
      if (isHistory.value) {
        Object.assign(params, {key: procModelKey})
      }
      return params
    },
  },
})

const [registerTable, {reload}, {rowSelection, selectedRowKeys}] = tableContext

const deploySelectVisible = ref<boolean>(false)
const editorModelId = ref<string>()

/**
 * 新增事件
 */
function handleAdd() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  })
}

/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  })
}

function handleDeploySelected(type: number) {
  deploySelectVisible.value = false
  if (type === 1) {
    window.open('http://localhost:7003/modeler.html?modelId=' + editorModelId.value, '_blank')
  } else if (type === 2) {
    openEditorModal(true, {
      modelId: editorModelId.value,
    })
  }
}

/**
 * 设计事件
 */
function handleDesign(record: Recordable) {
  editorModelId.value = record.id
  deploySelectVisible.value = true
}

/**
 * 部署事件
 * @param record
 */
function handleDeploy(record: Recordable) {
  openDeployModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  })
}

/**
 * 导出Xml
 */
function handleExportXml(record: Recordable) {
  registerModalXmlView.value.viewXml(record)
}

function handleHistoryModel(record: Recordable) {
  go('/activiti/model/history/' + record.key)
}

async function handleCopyModel(record: Recordable) {
  await copy(Object.assign({}, {
    modelId: record.id,
    name: record.name + "_Copy_" + new Date().getTime(),
    key: record.key + "_Copy_" + new Date().getTime(),
    category: record.category,
    description: record.description + "_Copy_" + new Date().getTime()
  }))
  handleSuccess()
}

/**
 * 删除事件
 */
async function handleDelete(record: any) {
  await deleteOne({id: record.id}, handleSuccess)
}

/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await batchDelete({ids: selectedRowKeys.value}, handleSuccess)
}

/**
 * 成功回调
 */
function handleSuccess() {
  ;(selectedRowKeys.value = []) && reload()
}

function handleDeploySuccess() {
}

/**
 * 操作栏
 */
function getTableAction(record: any) {
  return [
    {
      label: '编辑',
      onClick: handleEdit.bind(null, record),
      ifShow: () => {
        return hasPermission('act:model:edit')
      },
    },
    {
      label: '设计',
      onClick: handleDesign.bind(null, record),
      ifShow: () => {
        return hasPermission('act:model:design')
      },
    },
    {
      label: '部署',
      onClick: handleDeploy.bind(null, record),
      ifShow: () => {
        return hasPermission('act:model:deploy')
      },
    },
    {
      label: '导出',
      onClick: handleExportXml.bind(null, record),
      ifShow: () => {
        return hasPermission('act:model:exportXml')
      },
    }
  ]
}

function getDropDownAction(record: any) {
  return [
    {
      label: '历史版本',
      ifShow: !isHistory.value,
      onClick: handleHistoryModel.bind(null, record),
    },
    {
      label: '复制模板',
      popConfirm: {
        title: '是否确认复制模板',
        confirm: handleCopyModel.bind(null, record),
        placement: 'topLeft',
      },
      ifShow: () => {
        return hasPermission('act:model:copy')
      },
    },
    {
      label: '上传模板',

    },
    {
      label: '删除模板',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record),
        placement: 'topLeft',
      },
      ifShow: () => {
        return hasPermission('act:model:delete')
      },
    },
  ]
}
</script>

<style scoped></style>
